#!/usr/bin/env bash
#set -x
#SELFDIR=$(cd $(dirname "${BASH_SOURCE[0]}");pwd)

# $1 install
# $2 <module_name>
# $3 <module_version>
function main()
{
    if [[ $# -lt 2 ]]; then
        return 1
    fi

    if [[ ! -d "${PKGREPO}" ]]; then
        echo    "The required environment variable \${PKGREPO} is missing"
        return  1
    fi

    if [[ ! -d "${DEVREPO}" ]]; then
        echo    "The required environment variable \${DEVREPO} is missing"
        return  1
    fi

    #   加载公共的初始化脚本，以自身生成一些系统预定的环境变量
    source "${PKGREPO}/.share/module-install-init.bash" "$@"
    RESULT=$?
    if [[ ${RESULT} -ne 0 ]]; then
        echo    "Load the initialize script failed($RESULT)"
        return  1
    fi

    #   确定主包和主包内部目录
    local majorpkg=$(cat "${MODULE_VERSION_FILE}" | grep PACKAGE | awk '{print $3}')
    local innerdir=$(cat "${MODULE_VERSION_FILE}" | grep PACKAGE | awk '{print $4}')

    #   备份旧软件、创建构建目录、解压主软件包
    framework backup      &&  \
    framework maketransit &&  \
    framework unzip     "${MODULE_PACKAGE_DIR}/${majorpkg}"    "${MODULE_TRANSIT_DIR}"
    RESULT=$?
    if [[ ${RESULT} -ne 0 ]]; then
        echo    ""
        return  1
    fi

    #   编译和安装
    local builddir="${MODULE_TRANSIT_DIR}/${innerdir}"
    cd      "${builddir}"    &&  \
    cmake   -Bbuild -H. -DBUILD_TESTING=OFF -DCMAKE_INSTALL_PREFIX="${MODULE_INSTALL_DIR}"  &&  \
    cmake   --build build/ --target install  -j "${MODULE_TRANSIT_THREAD}" &&  \
    echo    "Build and install '${MODULE_LABEL}' success"
    RESULT=$?
    if [[ ${RESULT} -ne 0 ]]; then
        echo    "Build and install '${MODULE_LABEL}' failed(${RESULT}): '${MODULE_TRANSIT_DIR}'"
        return  1
    fi

    #   写 setup 文件
    touch "${MODULE_INSTALL_DIR}/setup.bash"
    echo "export ${MODULE_NAME_UPPER}_HOME=\"\${DEVREPO}/${MODULE_LABEL}\""   >>   "${MODULE_INSTALL_DIR}/setup.bash"
    #
    touch "${MODULE_INSTALL_DIR}/setup.csh"
    echo "setenv ${MODULE_NAME_UPPER}_HOME \"\${DEVREPO}/${MODULE_LABEL}\""   >>   "${MODULE_INSTALL_DIR}/setup.csh"

    return 0
}

main    "$@"
exit    "$?"
